package com.heima.behavior.interceptor;

import com.heima.utils.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
@Slf4j
public class AppTokenInterceptor implements HandlerInterceptor, Ordered {
    /**
     * 前后置拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("【前置拦截开始】");
        String userId = request.getHeader("userId");
        log.info("【用户id】:{}",userId);
        if(handler != null){
            UserThreadLocalUtil.setUser(Integer.parseInt(userId));
        }
        return true;
    }

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        /**
         * 结束
         */
        log.info("【拦截器结束执行】");
        //清理线程中的数据
        UserThreadLocalUtil.removeUser();
    }
}
